package cn.javase.base.annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;

public class AnnotationHandler {

    private static final Timer timer = new Timer(true);

    public static void handleSchedule(Object object) {
        Class<?> clazz = object.getClass();
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods) {
            method.setAccessible(true);
            if (method.isAnnotationPresent(Schedule.class)) {
                Schedule annotation = method.getAnnotation(Schedule.class);
                long delay = annotation.delay();
                long period = annotation.period();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            method.invoke(object);
                        } catch (IllegalAccessException | InvocationTargetException e) {
                            throw new RuntimeException(e);
                        }
                    }
                };
                timer.schedule(task, delay, period);
            }
        }
    }

}
